package com.yoyo.ad.utils;

import android.content.Context;
import android.content.SharedPreferences;


import java.util.Map;

public class SPUtils {

    private static final String FILE_NAME = "yoyo_ad_config";

    /**
     * 存入某个key对应的value值
     */
    public static void put(Context context, String key, Object value) {
        put(context, key, value, FILE_NAME);
    }

    public static void put(Context context, String key, Object value, String fileName) {
        SharedPreferences sp = context.getSharedPreferences(fileName, Context.MODE_PRIVATE);
        SharedPreferences.Editor edit = sp.edit();
        if (value instanceof String) {
            edit.putString(key, (String) value);
        } else if (value instanceof Integer) {
            edit.putInt(key, (Integer) value);
        } else if (value instanceof Boolean) {
            edit.putBoolean(key, (Boolean) value);
        } else if (value instanceof Float) {
            edit.putFloat(key, (Float) value);
        } else if (value instanceof Long) {
            edit.putLong(key, (Long) value);
        }
        edit.apply();
//        SharedPreferencesCompat.EditorCompat.getInstance().apply(edit);
    }

    /**
     * 得到某个key对应的值
     */
    public static Object get(Context context, String key, Object defValue) {
        return get(context, key, defValue, FILE_NAME);
    }

    public static Object get(Context context, String key, Object defValue, String fileName) {
        SharedPreferences sp = context.getSharedPreferences(fileName, Context.MODE_PRIVATE);
        if (defValue instanceof String) {
            if (key.equals("token"))
                return MD5Util.getMD5(sp.getString(key, (String) defValue));
            return sp.getString(key, (String) defValue);
        } else if (defValue instanceof Integer) {
            return sp.getInt(key, (Integer) defValue);
        } else if (defValue instanceof Boolean) {
            return sp.getBoolean(key, (Boolean) defValue);
        } else if (defValue instanceof Float) {
            return sp.getFloat(key, (Float) defValue);
        } else if (defValue instanceof Long) {
            return sp.getLong(key, (Long) defValue);
        }
        return null;
    }

    static String getId(Context context) {
        return (String) SPUtils.get(context, "id", "");
    }

    static String getToken(Context context) {
        return (String) SPUtils.get(context, "token", "");
    }
}
